package xyz.xuanlee.springcloud.loadbalancer;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLoadBalancerImpl implements IMyLoadBalancer {

    private AtomicInteger counter;

    public MyLoadBalancerImpl() {
        counter = new AtomicInteger(0);
    }

    @Override
    public ServiceInstance selectService(List<ServiceInstance> serviceInstances) {
        int totalInstance = serviceInstances.size();
        for (;;) {
            int cur = counter.get();
            int next = (cur + 1) % totalInstance;
            if (counter.compareAndSet(cur, next)) return serviceInstances.get(next);
        }
    }
}
